const path = require('path');
const fs = require('fs');
const os = require('os');

function getUserDataPath() {
    if (process.platform === 'darwin') {
        return path.resolve(os.homedir(), 'Library/Application Support/zzBim');
    }
    if (process.platform === 'win32') {
        return path.resolve(os.homedir(), 'AppData/Roaming/zzBim');
    }
    if (process.platform === 'linux') {
        return path.resolve(os.homedir(), '.config/zzBim');
    }
    return '';
}

class ConfigManager {
    constructor() {
        this.config = undefined;
    }

    async setup() {
        const _config = this.gather();
        this.config = _config;
        this.setLocal(_config);
    }

    get() {
        if (this.config) {
            return this.config;
        }
        const errMsg = '配置文件不存在';
        throw new Error(errMsg);
    }

    updateEnv(value) {
        const local = this.getEnvConfig();
        const _config = {...local, ...value };
        this.setEnvConfig(_config);
        return _config;
    }

    getLocal() {
        let globalConfig;
        const userDataPath = getUserDataPath();
        if (userDataPath) {
            const configFilePath = path.resolve(userDataPath, 'global.json');
            if (fs.existsSync(configFilePath)) {
                try {
                    const raw = fs.readFileSync(configFilePath, { encoding: 'utf8' });
                    const parsed = JSON.parse(raw);
                    // 处理如果读到的是 HTML 字符串的情况
                    if (typeof parsed === 'string') {
                        throw new Error(
                            'Parsed result is not JSON. Perhaps it parsed a HTML string'
                        );
                    }
                    globalConfig = parsed;
                } catch {}
            }
        }
        return globalConfig;
    }

    setLocal(data) {
        const userDataPath = getUserDataPath();
        if (userDataPath) {
            if (!fs.existsSync(userDataPath)) {
                // 不存在则创建文件夹
                fs.mkdirSync(userDataPath, { recursive: true });
            } else {
                const configFilePath = path.resolve(userDataPath, 'global.json');
                const content = JSON.stringify(data, null, 2);
                try {
                    console.log('写入配置成功');
                    fs.writeFileSync(configFilePath, content, { encoding: 'utf8' });
                } catch {
                    console.log('写入配置失败');
                }
            }
        }
    }

    updateConfig(value) {
        const local = this.getLocal();
        const _config = {...local, ...value };
        this.setLocal(_config);
        return _config;
    }

    getEnvConfig() {
        let configEnv;
        const userDataPath = getUserDataPath();
        if (userDataPath) {
            const configFilePath = path.resolve(userDataPath, 'env.json');
            if (fs.existsSync(configFilePath)) {
                try {
                    configEnv = JSON.parse(
                        fs.readFileSync(configFilePath, { encoding: 'utf8' })
                    );
                } catch (err) {}
            }
        }
        return configEnv;
    }

    setEnvConfig(data) {
        const userDataPath = getUserDataPath();
        if (userDataPath) {
            if (!fs.existsSync(userDataPath)) {
                // 不存在则创建文件夹
                fs.mkdirSync(userDataPath, { recursive: true });
            } else {
                const configFilePath = path.resolve(userDataPath, 'env.json');
                const content = JSON.stringify(data, null, 2);
                try {
                    fs.writeFileSync(configFilePath, content, { encoding: 'utf8' });
                } catch {
                    console.log('写入配置失败');
                }
            }
        }
    }

    getUpTaskConfig() {
        let configEnv;
        const userDataPath = getUserDataPath();
        if (userDataPath) {
            const configFilePath = path.resolve(userDataPath, 'uptask.json');
            if (fs.existsSync(configFilePath)) {
                try {
                    configEnv = JSON.parse(
                        fs.readFileSync(configFilePath, { encoding: 'utf8' })
                    );
                } catch (err) {}
            }
        }
        return configEnv;
    }
    setUpTaskConfig(data) {
        const userDataPath = getUserDataPath();
        if (userDataPath) {
            if (!fs.existsSync(userDataPath)) {
                // 不存在则创建文件夹
                fs.mkdirSync(userDataPath, { recursive: true });
            } else {
                const configFilePath = path.resolve(userDataPath, 'uptask.json');
                const content = JSON.stringify(data, null, 2);
                try {
                    fs.writeFileSync(configFilePath, content, { encoding: 'utf8' });
                } catch {
                    console.log('写入配置失败');
                }
            }
        }
    }

    updateUpTaskConfig(value) {
        const local = this.getUpTaskConfig();
        const _config = {...local, ...value };
        this.setUpTaskConfig(_config);
        return _config;
    }

    gather() {
        const localConfig = this.getLocal();
        if (localConfig) {
            return localConfig;
        }
        return {};
    }
}

module.exports = new ConfigManager();